<template>
  <el-drawer
    :visible.sync="isShowModal"
    size="800"
    :before-close="handleClose"
    :title="$t('message.pk')"
  >
    <el-form
      ref="ruleForm"
      class="doumee-form"
      :model="param"
      :rules="rules"
      label-width="auto"
      label-suffix="："
    >
      <el-form-item :label="$t('message.kcmc')">
        <el-input
          v-model="courseName"
          type="text"
          class="w400"
          :placeholder="$t('message.qsr') + $t('message.kcmc')"
          disabled
          maxlength="50"
        />
      </el-form-item>
      <el-form-item :label="$t('message.skjl2')">
        <el-select v-model="param.teacherId" :placeholder="$t('message.qxz') + $t('message.skjl2')" class="w400" clearable>
          <el-option
            v-for="item in jlList"
            :key="item.teacherId"
            :label="item.teacherName"
            :value="item.teacherId"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('message.zjjl')">
        <el-select v-model="param.assistantIds" :placeholder="$t('message.qxz') + $t('message.zjjl')" class="w400" multiple clearable>
          <el-option
            v-for="item in jlList"
            :key="item.teacherId"
            :label="item.teacherName"
            :value="item.teacherId"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('message.skddlx')" prop="siteType">
        <el-radio-group v-model="param.siteType ">
          <el-radio label="1">{{ $t('message.zdy') }}</el-radio>
          <el-radio label="2">{{ $t('message.xzcq') }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item v-if="param.siteType == 2" :placeholder="$t('message.xzcq')">
        <el-select v-model="param.areaId" :placeholder="$t('message.qxz') + $t('message.cq')" class="w400" @change="areaChange">
          <el-option
            v-for="item in areaList"
            :key="item.id"
            :label="item.areaName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item v-if="timeId" :label="$t('message.skrq')" prop="classDay">
        <el-date-picker
          v-model="param.classDay"
          :picker-options="pickerOptions"
          type="date"
          class="w400"
          value-format="yyyy-MM-dd"
          :placeholder="$t('message.xzrq')"
        />
      </el-form-item>
      <el-form-item v-if="timeId" :label="$t('message.sksj')" prop="time">
        <el-time-picker
          v-model="param.time"
          is-range
          value-format="HH:mm"
          format="HH:mm"
          class="w400"
          :clearable="false"
          :range-separator="$t('message.zhi')"
          :start-placeholder="$t('message.kssk')"
          :end-placeholder="$t('message.jssk')"
        />
      </el-form-item>
      <el-form-item v-if="!timeId" :label="$t('message.skrq')" prop="classDay">
        <el-date-picker
          v-model="param.classDay"
          type="daterange"
          class="w400"
          value-format="yyyy-MM-dd"
          :picker-options="pickerOptionb"
          :range-separator="$t('message.zhi')"
          :start-placeholder="$t('message.ksrq')"
          :end-placeholder="$t('message.jsrq')"
        />
      </el-form-item>
      <el-form-item v-if="!timeId" :label="$t('message.sksj')" prop="item">
        <div class="dayTime_wrap">
          <div v-for="ite,index in param.item" :key="index" class="mb10">
            <el-select v-model="ite.days" collapse-tags multiple class="mr10" style="width: 180px;" clearable :placeholder="$t('message.zjsk')">
              <el-option
                v-for="op in days"
                :key="op.id"
                :label="op.name"
                :value="op.id"
              />
            </el-select>
            <el-time-select
              v-model="ite.beginTime"
              :picker-options="{
                start: '06:00',
                step: '00:05',
                end: '22:00'
              }"
              :placeholder="$t('message.kssj')"
              class="w120 mr10"
              value-format="HH:mm"
              format="HH:mm"
              @change="selTimeChange(ite)"
            />
            <el-time-select
              v-model="ite.endTime"
              :picker-options="{
                start: ite.beginTime || '06:00',
                step: '00:05',
                end: '22:00'
              }"
              class="w120"
              :placeholder="$t('message.jssj')"
              value-format="HH:mm"
              format="HH:mm"
              @change="selTimeChange(ite)"
            />
            <span v-if="index !== 0" class="ml10 secondColor pointer" @click="dayTimeDel(index)">{{ $t('message.del') }}</span>
          </div>
          <div class="btn primaryColor" @click="handleDayTimeAdd">+{{ $t('message.zjsj') }}</div>
        </div>
      </el-form-item>
      <el-form-item :label="$t('message.skdd')" prop="site">
        <el-input
          v-model="param.site"
          type="text"
          :placeholder="$t('message.qsr') + $t('message.skdd')"
          class="w400"
          maxlength="50"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          :loading="subLoading"
          type="primary"
          @click="onSubmit()"
        >{{ $t('message.tj') }}</el-button>
      </el-form-item></el-form>
  </el-drawer>
</template>

<script>
import store from '@/store'
import { addCourseTime, infoCourse, teacherList, detailCourseTime, getAreaList } from '@/api'
import { shortcuts } from '@/utils/config'
import i18n from '@/utils/i18n'
export default {
  data() {
    var newRule = (rule, value, callback) => {
      console.log(value[0], 7, value[1])
      if (!value[0]) {
        callback(new Error(rule.message || this.$t('message.qxz') + this.$t('message.cq')))
      } else if (!value[1]) {
        callback(new Error(rule.message || this.$t('message.qxz') + this.$t('message.cd')))
      } else {
        callback()
      }
    }
    var newRuleb = (rule, value, callback) => {
      console.log(value[0], 7, value[1])
      if (value[0] === undefined && value[1] === undefined) {
        callback(new Error(rule.message || i18n.t('message.qsr') + i18n.t('message.kcrsfw')))
      } else if (!/^\+?[1-9][0-9]*$/.test(value[0]) || !/^\+?[1-9][0-9]*$/.test(value[1])) {
        callback(new Error(rule.message || i18n.t('message.qsr') + i18n.t('message.qrsr')))
      } else if (value[0] < 1) {
        callback(new Error(rule.message || i18n.t('message.qsr') + i18n.t('message.zqrsfw')))
      } else if (Number(value[0]) > Number(value[1])) {
        callback(new Error(rule.message || i18n.t('message.qsr') + i18n.t('message.zqrsfw')))
      } else {
        callback()
      }
    }
    return {
      courseId: '',
      classId: '',
      site: '',
      teacherId: '',
      timeId: '',
      isShowModal: false,
      subLoading: false,
      areaList: [],
      modalDialog: store.getters.dialog,
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < new Date(new Date().toLocaleDateString()).getTime()
        }
      },
      pickerOptionb: {
        shortcuts,
        disabledDate(time) {
          return (
            time.getTime() < new Date(new Date().toLocaleDateString()).getTime()
          )
        }
      },
      presentTime: new Date(new Date().toLocaleDateString()).getTime(),
      jlList: [],
      venueId: sessionStorage.getItem('venueId'),
      param: {
        venueId: sessionStorage.getItem('venueId'),
        siteType: '1',
        assistantIds: [],
        item: [
          {
            days: [],
            beginTime: '',
            endTime: ''
          }
        ]
      },
      closeDelay: 0,
      days: [
        { id: '1', name: this.$t('message.xq1') },
        { id: '2', name: this.$t('message.xq2') },
        { id: '3', name: this.$t('message.xq3') },
        { id: '4', name: this.$t('message.xq4') },
        { id: '5', name: this.$t('message.xq5') },
        { id: '6', name: this.$t('message.xq6') },
        { id: '7', name: this.$t('message.xq7') }
      ],
      rules: {
        site: [
          { required: true, message: this.$t('message.qsr') + this.$t('message.skdd'), trigger: 'blur' }
        ],
        dd: [
          { required: true, validator: newRule, trigger: ['change', 'change'] }
        ],
        teacherId: [
          { required: true, message: this.$t('message.qxz') + this.$t('message.skjl'), trigger: 'change' }
        ],
        classDay: [
          { required: true, message: this.$t('message.qxz') + this.$t('message.kkrq'), trigger: 'change' }
        ],
        classDay2: [
          { required: true, message: this.$t('message.qxz') + this.$t('message.jkrq'), trigger: 'change' }
        ],
        item: [
          { required: true, message: this.$t('message.qxz') + this.$t('message.sksj'), trigger: 'change' }
        ],
        days: [
          { required: true, message: this.$t('message.qxz') + this.$t('message.sksj'), trigger: 'change' }
        ],
        siteType: [
          { required: true, message: this.$t('message.qxz') + this.$t('message.skddlx'), trigger: 'change' }
        ],
        rs: [
          { required: true, validator: newRuleb, trigger: ['change', 'change'] }
        ]
      },
      courseName: '',
      courseItem: '',
      edit: false,
      activeDate: '',
      siteIds: [],
      projectId: '',
      reserveForm: [],
      numList: []
    }
  },
  created() {
    this.getTeachList()
    this.getAreaLists()
  },
  mounted() {
    this.activeDate = this.formatDate(new Date()).value
    // this.getDetail()
  },
  methods: {
    dayTimeDel(i) {
      const item = [...this.param.item]
      item.splice(i, 1)
      this.param.item = item
    },
    handleDayTimeAdd() {
      this.param.item.push({
        days: [],
        beginTime: '',
        endTime: ''
      })
    },
    handleClose() {
      this.isShowModal = false
      this.$emit('close')
    },
    getCourseTime() {
      detailCourseTime({ param: { timeId: this.timeId }}).then(res => {
        this.param = {
          ...res.record,
          assistantIds: res.record.assistantIds ? res.record.assistantIds : [],
          dayTime: [],
          time: [res.record.beginTime, res.record.endTime]
        }
      })
    },
    onSubmit() {
      const that = this
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          const param = JSON.parse(JSON.stringify(that.param))
          param.courseId = that.courseId
          param.classId = that.classId
          // const dayTime = {}
          if (!param.teacherId && (!param.assistantIds || param.assistantIds.length === 0)) {
            return this.$message.warning(this.$t('message.jlhzjbktswk'))
          }
          if (this.timeId) {
            param.beginTime = param.time[0]
            param.endTime = param.time[1]
            param.dayTime = null
          } else {
            // that.param.dayTime.forEach((item) => {
            //   if (!item.time) {
            //     pd = true
            //     return
            //   }
            //   dayTime[item.id] = item.time.join(',')
            //   param.dayTime = dayTime
            // })
            // param.days = that.param.days.join(',')
            param.classDay2 = that.param.classDay[1]
            param.classDay = that.param.classDay[0]
            let count = 0
            param.item.forEach(item1 => {
              if (item1.days.length === 0 || !item1.beginTime || !item1.endTime) {
                count++
              }
              item1.days = item1.days.join(',')
            })
            if (count > 0) {
              console.log(param.item)
              return this.$message.warning(this.$t('message.qxxzsksj'))
            }
          }
          this.subLoading = true
          addCourseTime({
            param
          }).then(res => {
            this.subLoading = false
            if (res.errorCode === '000000') {
              that.$message.success(this.$t('message.tjcg'))
              this.isShowModal = false
              this.$emit('success')
              this.$emit('close')
            }
          }).catch(err => {
            this.subLoading = false
            console.log(err)
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    areaChange(id) {
      const item = this.areaList.find(i => i.id === id)
      this.$set(this.param, 'site', item.areaName)
      this.$set(this.param, 'areaName', item.areaName)
    },
    getAreaLists() {
      getAreaList({ param: { venueId: this.venueId }}).then(res => {
        this.areaList = res.recordList || []
      })
    },
    addDay(v) {
      const that = this
      this.param.dayTime = []
      v.forEach(id => {
        that.param.dayTime.push(that.days.find((item) => item.id === id))
      })
    },
    replacementBtn(e) {
      this.siteIds = e.siteIds
      this.reserveForm = e.reserveForm
      const arr = this.reserveForm
      if (arr.length > 0) {
        this.$set(this.param, 'classDay', arr[0].day)
        const ksList = []
        const jsList = []
        const siteList = []
        arr.forEach(e => {
          ksList.push(e.beginTime)
          jsList.push(e.endTime)
          siteList.push(e.name)
        })
        const ks = ksList[0].replace(':', '')
        const js = jsList[0].replace(':', '')
        let ksIndex = 0
        let jsIndex = 0
        ksList.forEach((e, index) => {
          if (ks > e.replace(':', '')) {
            ksIndex = index
          }
        })
        jsList.forEach((e, index) => {
          if (js < e.replace(':', '')) {
            jsIndex = index
          }
        })
        this.$set(this.param, 'time', [ksList[ksIndex], jsList[jsIndex]])
        this.$set(this.param, 'site', Array.from(new Set(siteList)).join(','))
        this.$set(this.param, 'siteId', this.siteIds.join(','))
      }
    },
    showCc() {
      this.activeDate = this.formatDate(new Date()).value
      this.$refs.replacement.showBtn(this.activeDate, this.projectId, [])
    },
    // 获取星期
    calculation(s) {
      return s < 10 ? '0' + s : s
    },
    formatDate(date) {
      const year = date.getFullYear() + '-'
      const month = this.calculation(date.getMonth() + 1) + '-'
      const day = this.calculation(date.getDate())
      const week = [this.$t('message.z7', this.$t('message.z1'), this.$t('message.z2'), this.$t('message.z3'), this.$t('message.z4'), this.$t('message.z5'), this.$t('message.z6'))][date.getDay()]
      return {
        label: month + day + ' ' + week,
        value: year + month + day,
        old: new Date(date)
      }
    },
    // 星期结束
    getTeachList(page) {
      const venueId = sessionStorage.getItem('venueId')
      teacherList({ param: { venueId, teacherType: '0', isOnJob: '1', status: '1' }}).then(res => {
        this.jlList = res.recordList
      })
    },
    getDetail() {
      // 获取卡类型列表
      infoCourse({ param: { courseId: this.courseId }})
        .then((res) => {
          if (res.errorCode !== '000000') return
          const obj = res.record
          this.courseItem = obj.courseItem
          this.courseName = obj.courseName
          this.projectId = obj.courseItemIds
          this.$set(this.param, 'teacherId', this.teacherId)
          this.$set(this.param, 'site', this.site)
        })
        .catch((err) => {
          console.log(err)
        })
    },
    selTimeChange(item) {
      console.log(item)
      if (item.beginTime && item.endTime && item.beginTime > item.endTime) {
        item.endTime = null
        return this.$message.warning(this.$t('message.jssjydykssj'))
      }
    }
  }
}
</script>

<style lang="scss" scoped>
@import "@/styles/variables.scss";
.device-uploader {
  width: 80px;
  height: 80px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fff;
  cursor: pointer;
  border: 1px dashed #ccc;
  border-radius: 8px;
  transition: all 0.3s;
  margin-right: 20px;
  &:hover {
    border-color: $menuActive;
    .uploader-icon {
      color: $menuActive;
    }
  }
  ::v-deep .el-upload {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
    .file {
      width: 100%;
      height: 100%;
      position: absolute;
      top: 0;
      left: 0;
      background-size: contain;
      background-position: center;
      background-repeat: no-repeat;
      border-radius: 8px;
      display: flex;
      align-items: center;
      justify-content: center;
      .delete {
        background-color: rgba(0, 0, 0, 0.5);
        position: absolute;
        width: 100%;
        height: 100%;
        top: 0;
        left: 0;
        display: none;
        align-items: center;
        justify-content: center;
        .icon {
          color: #fff;
        }
      }
      &:hover {
        .delete {
          display: flex;
        }
      }
    }
  }
  .uploader-icon {
    color: #aaaaaa;
    font-size: 22px;
    transition: all 0.3s;
  }
}
.dayTime_wrap{
  .btn{
    background-color: #f5f7fc;
    border-radius: 6px;
    width: 480px;
    padding: 2px 0;
    text-align: center;
    cursor: pointer;
    margin-top: 10px;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}
.line-style {
  margin-bottom: 20px;
}
.device-uploaders {
  ::v-deep .el-upload-list__item {
    width: 80px;
    height: 80px;
  }
  ::v-deep .el-upload {
    width: 80px;
    height: 80px;
    line-height: 80px;
  }
}
</style>
